using System;
using System.Collections.Generic;
using SpecMaker.Core.Dsl;
using SpecMaker.Core.Exceptions;

namespace SpecMaker.Core
{
    public class RuleExecutor
    {
        public RuleResult[] Spec(Spec spectorun)
        {
            var results = new List<RuleResult>();

            foreach (RuleSet rules in spectorun.Actions)
            {
                var result = RunRule(rules.Action, rules.Rule); 
                results.Add(result);
            }
            return results.ToArray();
        }

        private RuleResult RunRule(Action action, string rule)
        {
            var ruleresult = new RuleResult() {Description = rule};
            try
            {
                try
                {
                    try
                    {
                        action.Invoke();
                    }
                    catch (RuleException)
                    {
                        ruleresult.Status = RuleStatus.Failed;
                        return ruleresult;
                    }
                }
                catch (PendingException)
                {
                    ruleresult.Status = RuleStatus.Pending;
                    return ruleresult;
                }
            }
            catch (Exception ex)
            {
                ruleresult.Status = RuleStatus.Error;
                ruleresult.ErrorMessage = "Message: " + ex.Message + "\n" + "Stackstrace: " + ex.StackTrace;
                return ruleresult;
            }
            ruleresult.Status = RuleStatus.Passed;
            return ruleresult;
        }
    }
    }
